import { Component, EventEmitter, HostBinding, Input, NgZone, OnInit, Output, TemplateRef, ViewChild } from '@angular/core';
import { DesignerEnvType, DomService, FormBasicService, FormComponentType, FormSchemaEntity, FormSchemaEntityField, SchemaService } from '@farris/designer-services';
import { NotifyService } from '@farris/ui-notify';
import { TreeTableComponent } from '@farris/ui-treetable';
import { cloneDeep } from 'lodash-es';
import { DgControl } from '@farris/designer-services';
import { ComponentBuildInfo } from './inner-component-build-info';

/**
 * 创建组件：
 * 场景1：控件工具箱中拖拽Form DataGrid图标。传入组件类型（componentType），需要用户选择实体和实体展示字段
 * 场景2：实体树中拖拽实体节点。传入实体id（fixedEntityId），需要用户选择组件类型、（实体）、实体展示字段
 * 场景3：控件树中点击组件节点右键菜单，创建同级组件或者选中标签页添加子级DataGrid。传入组件类型（componentType），需要用户选择实体和实体展示字段
 */
@Component({
    selector: 'inner-component-creator',
    templateUrl: './inner-component-creator.component.html',
    styleUrls: ['./inner-component-creator.component.css']
})
export class InnerComponentCreatorComponent implements OnInit {
    @HostBinding('class')
    cls = 'd-flex f-utils-fill-flex-column h-100';

    @ViewChild('btns') btns: TemplateRef<any>;

    /** 需要创建的组件类型: form/Form/form-col-xx/DataGrid/ListView/FileUploadPreview */
    @Input() componentType = '';

    /** 允许选择的实体级别，不填则不限制。 1：主表；2：从表；3从从表 */
    @Input() allowedEntityLevel: number;

    /** 固定选择实体Id.用于实体树上实体节点拖拽生成控件时使用。 */
    @Input() fixedEntityId = '';

    /** 展示字段列表是否需要排除掉已添加的字段----默认排除 */
    @Input() needExcludeDisplayedFields = true;

    /** 实体列表是否需要排除掉已使用的实体----默认不排除 */
    @Input() needExcludeDisplayedEntity = false;

    /** 目标组件是否在侧边栏中 */
    @Input() bindingTargetInSidebar: boolean;

    /* 保存前事件，用于保存前的扩展操作 */
    @Output() beforeSave = new EventEmitter<any>();

    @Output() save = new EventEmitter<ComponentBuildInfo>();

    @Output() cancel = new EventEmitter<ComponentBuildInfo>();

    // 步骤条信息
    activeIndex = 0;
    currentId = 'selectTable';
    stepMessages = [];

    // 实体树表实例
    @ViewChild('schemaTree') schemaTree: TreeTableComponent;

    /** 实体树表数据源 */
    schemaSource = [];

    /** 实体树表列配置 */
    schemaTreeColumns = [{ field: 'name', title: '名称' }];

    /**  选中的实体表 */
    selectedEntity;
    /** 选中的表节点（树节点） */
    selectedEntityTreeNode;

    /** 默认选中的表ID */
    defaultSelectedCmp: any;


    /** 是否选中主表 */
    isSelectMainTable = false;

    /** 记录主表信息 */
    mainTable;

    /** 记录所有表的编号信息，便于在新增子表是查重 */
    tableCodes = [];

    /** 展示字段树表实例 */
    @ViewChild('fieldsTree') fieldsTree: TreeTableComponent;
    /** 展示字段树表数据源 */
    fieldsSource = [];
    /** 展示字段树表列配置 */
    filedsTreeColumns = [
        { field: 'name', title: '字段名称' }, { field: 'bindingField', title: '绑定字段' },
        { field: 'type', title: '字段类型', width: 100 }, { field: 'show', title: '显示', width: 120 }
    ];
    /** 是否全选字段 */
    selectedAllFields = false;
    /** 字段勾选配置 */
    selected = {};
    /** 选中的字段 */
    selectedFields = [];
    /** 筛选是否为parentID && id */
    bindingFields = [];
    /** 组件的构造信息 */
    buildInfo: ComponentBuildInfo = {
        componentId: '',
        componentIdPrefix: '',
        componentName: '',
        componentType: '',
        componentAppearance: '',
        resolvedComponentType: '',
        formColumns: 4,
        parentContainerId: null,
        editable: true, // 目前列表类型组件只能选择子表，并且均可编辑
        selectedFields: [],
        bindTo: '',
        dataSource: ''
    };

    /** 当前表单schema实体 */
    schemaEntity;

    /** 表单中已添加的字段集合，用于添加卡片组件时排除掉页面中已创建过控件的字段 */
    displayedFieldsMap = new Map<string, boolean>();

    /** 选中的实体下是否包含可勾选的字段，用于没有可选字段时不显示全选按钮 */
    hasSelectableFields = false;

    /** 表单中已创建过的列表label结合，用于添加列表组件时排除掉页面中已创建过列表的实体 */
    private engagedEntityLabels: Set<string>;

    /** DOM结构中Component节点记录的componentType */
    private resolvedComponentType;

    /** 是否需要用户选择组件类型 */
    needSelectComponentType = false;

    /** 可选的组件类型 */
    componentTypeList = [];

    /** 组件标题 */
    componentName: string;

    /** 当前设计器运行环境是否为零代码环境 */
    isNoCodeDesingerEnv: boolean;

    /** 当前设计器运行环境是否为零代码环境 */
    desingerEnv: any;
    constructor(
        private notifyService: NotifyService,
        private domServ: DomService,
        private schemServ: SchemaService,
        private formBasicServ: FormBasicService,
        private ngZone: NgZone) { }


    ngOnInit() {
        if (!this.componentType) {
            this.componentType = '';
        }

        this.isNoCodeDesingerEnv = this.formBasicServ && this.formBasicServ.envType === DesignerEnvType.noCode;
        this.desingerEnv = this.formBasicServ && this.formBasicServ.envType;

        this.initProgressData();
        this.currentId = this.stepMessages[0].id;

        // 现有的schema实体
        const entityOrigin = this.schemServ.getSchemaEntities();
        this.schemaEntity = cloneDeep(entityOrigin);

        this.assembleSchemaSource();

        // 默认排除已选字段
        if (this.needExcludeDisplayedFields === undefined) {
            this.needExcludeDisplayedFields = true;
        }

        this.needSelectComponentType = !this.componentType;
        if (this.componentType) {
            this.resolvedComponentType = this.getComponentResolovedType();
        }
    }

    /**
     * 步骤条信息
     */
    private initProgressData() {
        // 不确定组件类型、确定绑定实体：场景为实体树拖实体节点
        if (!this.componentType && this.fixedEntityId) {
            this.stepMessages = [
                { id: 'selectComponentType', title: '选择组件类型' },
                { id: 'selectShowFields', title: '选择显示字段' }
            ];
            return;
        }
        // 确定组件类型、确定绑定实体：场景为控件树Form组件增加同级
        if (this.componentType && this.fixedEntityId) {
            this.stepMessages = [
                { id: 'selectShowFields', title: '选择显示字段' }
            ];
            return;
        }
        // 工具箱拖附件，只需要选择实体，不需要选择字段
        if (this.componentType === 'FileUploadPreview' || this.componentType === 'ListView') {
            if (this.desingerEnv === DesignerEnvType.mobileDesigner) {
                this.stepMessages = [
                    { id: 'selectTable', title: '选择实体' },
                    { id: 'selectShowFields', title: '选择显示字段' }
                ];
            } else {
                this.stepMessages = [
                    { id: 'selectTable', title: '选择实体' }
                ];
            }

            return;
        }

        // 移动附件列表添加
        if (this.componentType === 'ChildAttachList' || this.componentType === 'Attachment') {
            this.stepMessages = [
                { id: 'selectTable', title: '选择实体' }
            ];
            return;
        }
        if (this.componentType === 'AttachmentEntry') {
            this.stepMessages = [
                { id: 'selectTable', title: '选择实体' },
                { id: 'selectShowFields', title: '选择显示字段 (可选)' }
            ];
            return;
        }

        // 工具箱拖Form、DataGrid...不限制实体，都可以选择
        this.stepMessages = [
            { id: 'selectTable', title: '选择实体' },
            { id: 'selectShowFields', title: '选择显示字段' }
        ];


    }

    /**
     * 组装实体树
     */
    assembleSchemaSource() {
        const schemaTree = this.assembleSchemaBasicInfo2Tree(this.schemaEntity[0], 1);
        this.schemaSource = [schemaTree];
        if (this.defaultSelectedCmp) {
            this.ngZone.runOutsideAngular(() => {
                setTimeout(() => {
                    this.schemaTree.selectNode(this.defaultSelectedCmp.id);

                    // 若没有选择实体的步骤，则需要初始字段列表
                    if (!this.stepMessages.find(step => step.id === 'selectTable')) {

                        // 获取选中实体
                        this.selectedEntity = this.defaultSelectedCmp;
                        if (this.needSelectComponentType) {
                            this.getSelectablecomponentLists();
                        }

                        this.assembleSchemaFields();
                    }
                });
            });
        } else {

        }
    }
    /**
     * 将schema实体组装成树
     * 规则： 卡片类型组件只能选择主表，列表类型组件只能选择从表
     */
    private assembleSchemaBasicInfo2Tree(schemaEntity: FormSchemaEntity, level: number) {
        const result = {
            data: schemaEntity,
            expanded: true,
            children: [],
            selectable: false
        };
        if (level === 1) {
            // 主表支持配置为卡片、列表、表格
            this.tableCodes = [];
            this.mainTable = schemaEntity;

            // if (this.componentType.toLowerCase().startsWith('form') || this.componentType === 'ListView') {
            result.selectable = this.fixedEntityId ? schemaEntity.id === this.fixedEntityId : true;
            // }
        } else {
            // 不限制实体绑定次数
            if (this.needExcludeDisplayedEntity) {
                const entityEngaged = this.checkEntityEngaged(schemaEntity);
                result.selectable = this.fixedEntityId ? schemaEntity.id === this.fixedEntityId && !entityEngaged : !entityEngaged;
            } else {
                result.selectable = this.fixedEntityId ? schemaEntity.id === this.fixedEntityId : true;
            }
        }

        // 判断允许选择的实体层级
        if (this.allowedEntityLevel && level !== this.allowedEntityLevel) {
            result.selectable = false;
        }

        result.selectable = this.checkAttachmentBindingCondition(schemaEntity) && result.selectable;

        if (result.selectable) {
            this.defaultSelectedCmp = this.defaultSelectedCmp || schemaEntity;
        }

        this.tableCodes.push(schemaEntity.code);

        if (schemaEntity.type.entities && schemaEntity.type.entities.length) {
            const childTable = schemaEntity.type.entities.map(ele => this.assembleSchemaBasicInfo2Tree(ele, level + 1));
            result.children.push(...childTable);
        }

        return result;
    }

    /**
     * 校验与附件相关的绑定条件
     * @param schemaEntity 实体
     */
    checkAttachmentBindingCondition(schemaEntity: FormSchemaEntity) {
        if (!['FileUploadPreview', 'DataGrid', 'ChildAttachList', 'AttachmentEntry', 'Attachment'].includes(this.componentType)) {
            return true;
        }
        let haveAttachField = false;
        if (schemaEntity.type && schemaEntity.type.fields) {
            schemaEntity.type.fields.find((fitled) => {
                if (fitled.type &&
                    fitled.type.$type === 'ObjectType' &&
                    fitled.type.fields &&
                    fitled.type.fields.length >= 4 &&
                    fitled.type.fields[0].code === 'AttachmentId' &&
                    fitled.type.fields[1].code === 'FileName' &&
                    fitled.type.fields[2].code === 'FileSize' &&
                    fitled.type.fields[3].code === 'FileCreateTime'
                ) {
                    haveAttachField = true;
                    return true;
                }
                return false;
            });
        }
        // 附件控件只能绑定带附件字段的实体
        if (this.componentType === 'FileUploadPreview' && !haveAttachField) {
            return false;
        }

        // 零代码：列表控件不能绑定带附件的实体
        if (this.isNoCodeDesingerEnv && this.componentType === 'DataGrid' && haveAttachField) {
            return false;
        }

        // 移动附件子表
        if ((this.componentType === 'ChildAttachList' || this.componentType === 'AttachmentEntry' || this.componentType === 'Attachment') && !haveAttachField) {
            return false;
        }

        return true;
    }

    /**
     * 切换选中的实体节点
     */
    selectedEntityChanged(selectedEntityNode: any) {
        this.selectedAllFields = false;
        this.selected = {};
        this.selectedFields = [];
        this.selectedEntityTreeNode = selectedEntityNode.node;
        this.isSelectMainTable = !selectedEntityNode.node.parent;
    }

    clickSelectAllFieldsCheckbox() {
        this.selectedFields = [];
        this.selectAllChange(this.fieldsSource);

    }

    selectAllChange(fieldsSource) {
        if (fieldsSource.length === 0) {
            return;
        }
        fieldsSource.forEach(fieldTreeNode => {
            const bindingField = fieldTreeNode.data.bindingField;
            if (fieldTreeNode.children && fieldTreeNode.children.length > 0) {
                this.selectAllChange(fieldTreeNode.children);
            } else {
                if (fieldTreeNode.selectable) {
                    this.selected[bindingField] = this.selectedAllFields;
                    if (this.selectedAllFields) {
                        this.selectedFields.push(fieldTreeNode.data);
                    }
                }

            }
        });
    }

    clickCheckbox(flag: boolean, rowData: any) {
        if (flag) {
            this.selectedFields.push(rowData);
            const fieldCheckboxCount = this.fieldsTree.el.nativeElement.getElementsByClassName('k-checkbox').length - 1;
            if (this.selectedFields.length === fieldCheckboxCount) {
                this.selectedAllFields = true;
            }
        } else {
            this.selectedFields = this.selectedFields.filter(f => f.bindingField !== rowData.bindingField);
            this.selectedAllFields = false;
        }
    }

    /**
     * 下一步
     */
    clickNextStep() {
        switch (this.currentId) {
            case 'selectTable': {
                if (!this.schemaTree.selectedRow) {
                    this.notifyService.warning('请先选择实体');
                    return;
                }
                // 获取选中实体
                this.selectedEntity = this.schemaTree.selectedRow.data;

                if (this.needSelectComponentType) {
                    this.getSelectablecomponentLists();
                }

                this.assembleSchemaFields();
                break;
            }
            case 'selectComponentType': {
                if (!this.componentType) {
                    this.notifyService.warning('请先选择组件类型');
                    return;
                }
                if (!this.componentName) {
                    this.notifyService.warning('请先填写组件标题');
                    return;
                }
                this.resolvedComponentType = this.getComponentResolovedType();
                this.assembleSchemaFields();
                this.selectedFields = [];
                this.selectedAllFields = false;
                this.selected = {};
                break;
            }
        }
        this.activeIndex = this.activeIndex + 1;
        this.currentId = this.stepMessages[this.activeIndex].id;

        // 零代码：默认选中所有可选字段
        if (this.isNoCodeDesingerEnv) {
            this.selectedAllFields = true;
            this.selectAllChange(this.fieldsSource);
        }

    }
    /**
     * 组装字段列表
     */
    assembleSchemaFields() {
        const fields = this.selectedEntity.type.fields;

        this.displayedFieldsMap.clear();
        this.getDisplayedFieldsMapBySelectedEntity();


        this.hasSelectableFields = false;
        this.fieldsSource = this.assembleFields2Tree(fields, true);
    }
    private getSelectablecomponentLists() {
        let attachmentCode = [];
        for (let i = 0; i < this.selectedEntity.type.fields.length; i++) {
            attachmentCode.push(this.selectedEntity.type.fields[i].code);
        }
        // 主表
        if (this.isSelectMainTable) {
            this.componentTypeList = [{ text: '卡片面板', value: 'Form' }, { text: '表格', value: 'DataGrid' }];
        } else if (attachmentCode.includes("Attachment")) {
            this.componentTypeList = [{ text: '附件', value: 'FileUploadPreview' }];
        } else {
            // 子表
            this.componentTypeList = [{ text: '表格', value: 'DataGrid' }, { text: '卡片面板', value: 'Form' }];
        }
        if (!this.componentType) {
            this.componentType = this.componentTypeList[0].value;
        }
        if (!this.componentName) {
            this.componentName = this.selectedEntity.type.displayName;
        }

        /** 拖入附件 立即创建 */
        // let attachmentCode = [];
        // for(let i = 0;i< this.selectedEntity.type.fields.length;i++){
        //     attachmentCode.push(this.selectedEntity.type.fields[i].code);
        // }
        // if(attachmentCode.includes("Attachment")){
        //     this.componentTypeList =[{text: '附件', value: 'FileUploadPreview'}];
        //     this.componentType = this.componentTypeList[0].value;
        //     this.selectedAllFields = true;
        //     this.clickSave();
        // }
    }
    /**
     * 上一步
     */
    clickPreStep() {
        this.activeIndex = this.activeIndex - 1;
        this.currentId = this.stepMessages[this.activeIndex].id;
    }
    /**
     * schema字段集合组装成树
     * @param fields schema字段集合
     */
    private assembleFields2Tree(fields: FormSchemaEntityField[], expandRelateNode = true) {
        const treeData = [];
        fields.forEach(element => {
            // 关联表字段 / UDT字段
            let children = [];
            if (element.type && element.type.fields && element.type.fields.length > 0) {
                children = this.assembleFields2Tree(element.type.fields, true);
            }
            let selectable = this.displayedFieldsMap ?
                children.length === 0 && !this.displayedFieldsMap.has(element.id) : children.length === 0;

            // 零代码： ID与ParentID字段不可选
            if (this.isNoCodeDesingerEnv && (element.code === 'ID' || element.code === 'ParentID')) {
                selectable = false;
            }
            if (selectable) {
                this.hasSelectableFields = true;
            }
            treeData.push({
                data: element,
                children,
                expanded: expandRelateNode,
                selectable
            });
        });
        return treeData;
    }


    /**
     * 获取指定实体中已在当前表单中被占用的字段，场景：创建卡片组件时将已在其他组件中添加的字段排除掉
     */
    private getDisplayedFieldsMapBySelectedEntity() {
        if (!this.selectedEntity) {
            this.displayedFieldsMap.clear();
            return;
        }

        // 根组件和table组件内的输入控件与form内不能重复
        let targetCmpType = this.resolvedComponentType;
        if (targetCmpType === 'Frame' || targetCmpType === 'table' || (targetCmpType && targetCmpType.startsWith('form'))) {
            targetCmpType = 'form';
        }

        this.domServ.viewmodels.forEach(viewModel => {
            if (!viewModel.fields || viewModel.fields.length === 0) {
                return;
            }
            const componentNode = this.domServ.getComponentByVMId(viewModel.id);
            // 绑定同一个实体，并且是同类型的组件（form类、dataGrid类...）
            let sourceCmpType = componentNode.componentType;
            if (sourceCmpType === 'Frame' || sourceCmpType === 'table' || (sourceCmpType && sourceCmpType.startsWith('form'))) {
                sourceCmpType = 'form';
            }
            const entityInfo = this.schemServ.getTableInfoByViewModelId(viewModel.id);

            if (sourceCmpType !== targetCmpType || entityInfo.id !== this.selectedEntity.id) {
                return;
            }
            /** 组件是否在侧边栏中 */
            const componentInSidebar = this.checkComponentIfInSidebar(componentNode.id);


            // 若当前组件在侧边栏中，那么只收集同样在侧边栏中的字段。
            if (this.bindingTargetInSidebar && componentInSidebar) {
                viewModel.fields.forEach(field => {
                    this.displayedFieldsMap.set(field.id, true);
                });

            }

            // 若当前组件不在侧边栏中，那么只收集不在侧边栏中的字段
            if (!this.bindingTargetInSidebar && !componentInSidebar) {
                viewModel.fields.forEach(field => {
                    this.displayedFieldsMap.set(field.id, true);
                });

            }

            // if () {
            //     viewModel.fields.forEach(field => {
            //         this.displayedFieldsMap.set(field.id, true);
            //     });
            // }
        });

    }

    /**
     * 触发保存
     */
    clickSave() {
        let execute = false;
        if (this.isNoCodeDesingerEnv && this.fieldsSource.length === 2) {
            for (let i = 0; i < this.fieldsSource.length; i++) {
                this.bindingFields.push(this.fieldsSource[i].data.bindingField);
                if (this.bindingFields.includes('parentID') && this.bindingFields.includes('id')) {
                    execute = true;
                }
            }
        }
        if (this.componentType === 'FileUploadPreview'
            || this.componentType === 'ListView'
            || this.componentType === 'ChildAttachList'
            || this.componentType === 'AttachmentEntry'
            || this.componentType === 'Attachment'
        ) {
            if (!this.schemaTree.selectedRow) {
                this.notifyService.warning('请先选择实体');
                return;
            }
            this.selectedEntity = this.schemaTree.selectedRow.data;
        } else {
            if (this.selectedFields.length === 0 && !execute) {
                this.notifyService.warning('请先选择字段');
                return;
            }
        }

        if (this.desingerEnv === DesignerEnvType.mobileDesigner && this.selectedFields.length === 0 && this.componentType === 'ListView') {
            this.notifyService.warning('请先选择字段');
            return;
        }


        this.buildInfo.componentId = this.selectedEntity.code.toLowerCase() + '-' + Math.random().toString(36).slice(2, 6);
        this.buildInfo.componentIdPrefix = this.buildInfo.componentId + '-component';
        this.buildInfo.componentName = this.componentName || this.selectedEntity.type.displayName;
        this.buildInfo.componentType = this.componentType;
        // this.buildInfo.componentAppearance = this.getComponentAppearance();
        this.buildInfo.resolvedComponentType = this.resolvedComponentType;
        this.buildInfo.formColumns = 4;
        this.buildInfo.parentContainerId = '';
        this.buildInfo.selectedFields = this.selectedFields;
        this.buildInfo.bindTo = '/' + this.getViewModelBindTo(this.selectedEntityTreeNode);
        this.buildInfo.dataSource = this.selectedEntity.label;

        // 创建附件时保存选中的实体，用于获取实体中的附件udt
        if (this.componentType === 'FileUploadPreview') {
            this.buildInfo.selectedEntity = this.selectedEntity;
        }

        this.save.emit(this.buildInfo);
    }

    /**
     * 取消
     */
    clickCancel() {
        this.cancel.emit();
    }

    /**
     * 根据组件类型获取DOM中Component节点的componentType属性
     */
    private getComponentResolovedType() {
        switch (this.componentType) {
            case 'form': case 'Form': {
                // 这里默认为form-col-4
                return this.componentType.toLowerCase() + '-col-' + this.buildInfo.formColumns;
            }
            case 'DataGrid': case 'TreeGrid': {
                return FormComponentType.dataGrid;
            }
            case 'ListView':
                return FormComponentType.listView;
            case 'FileUploadPreview':
                return FormComponentType.attachmentPanel;

            default: {
                if (this.componentType.startsWith('form-col-')) {
                    return this.componentType;
                }
            }
        }
    }

    /**
     * 组装viewModel bindTo属性
     * @param node schema节点
     */
    private getViewModelBindTo(node: any) {
        let parentLabel = '';
        if (node.parent && node.parent.parent) {
            parentLabel = this.getViewModelBindTo(node.parent) + '/';
        }
        if (node.parent) {
            return parentLabel + node.data.label;
        }

        return '';
    }


    /**
     * 检查实体是否被使用了
     * 同一类型的组件中是否已使用过实体
     * @param schemaEntity 被检查的实体
     */
    private checkEntityEngaged(schemaEntity: FormSchemaEntity) {
        const targetCmpType = this.getComponentResolovedType();

        if (!this.engagedEntityLabels) {
            this.engagedEntityLabels = new Set<string>();
            const vms = this.domServ.viewmodels;
            vms.forEach(vm => {
                if (vm.bindTo === '/' || vm.fakeDel) {
                    return; // 跳过对主表的处理
                }
                const cmp = this.domServ.getComponentByVMId(vm.id);
                if (cmp && cmp.componentType === targetCmpType) {
                    const lastSlashIndex = vm.bindTo.lastIndexOf('/');
                    const tableCode = vm.bindTo.slice(lastSlashIndex + 1);
                    this.engagedEntityLabels.add(tableCode);
                }

                // 临时修改：兼容移动端
                if (
                    this.componentType === 'ChildList'
                    || this.componentType === 'ChildAttachList'
                    || this.componentType === 'AttachmentEntry'
                    || this.componentType === 'Attachment'
                ) {
                    const lastSlashIndex = vm.bindTo.lastIndexOf('/');
                    const tableCode = vm.bindTo.slice(lastSlashIndex + 1);
                    this.engagedEntityLabels.add(tableCode);
                }
            });
        }

        return this.engagedEntityLabels.has(schemaEntity.label);
    }

    /**
     * 检查卡片组件是否在侧边栏中，在侧边栏中的字段可以与非侧边栏中的字段重复。
     */
    private checkComponentIfInSidebar(cmpNodeId: string) {
        const sidebar = this.domServ.selectNode(this.domServ.components[0],
            item => item.type === DgControl.Sidebar && DgControl.Sidebar && DgControl.Sidebar.type && item.contents && item.contents.length &&
                item.contents.find(child => child.type === DgControl.ComponentRef.type && child.component === cmpNodeId));
        if (sidebar) {
            return true;
        }
        return false;
    }
}
